import { ElForm, ElFormItem, ElButton } from 'element-plus'
import {defineComponent, ref, reactive, toRefs, onMounted, onUpdated, toRaw} from 'vue'
import { useDebounceFn } from '@vueuse/core'
import { arrangeAssignment } from './config/index.js'

const FormSearch = defineComponent({
    name: 'formSearch',
    props: {
        FormShow: {
            type: Boolean,
            default: true
        },
        FormRules: {
            type: Array,
            required: true,
        },
        FormParams: {
            type: Object,
            default: () => {}
        },
        FormAttrs: {
            type: Object,
            default: {
                size: 'default',
                inline: true
            }
        }
    },
    setup(props, {emit, expose }) {
        onMounted(() => {
            createForm()
        })

        const { FormParams: formParams } = toRefs(props)


        // 表单配置数据
        const formRules = ref([])

        // 初始化表单数据
        function createForm() {
            formRules.value = props.FormRules.map(item => {
                if(item.hasOwnProperty('props')) {
                    const { props } = item
                    formParams.value[props.prop] = undefined
                    // 根据label字数设置动态宽度
                    props.labelWidth = (props.label.length * 20) + 'px'
                }
                return toRaw(item)
            })
        }

        const handleRefresh = () => {
            for(let key in formParams.value) {
                if(key !== 'pageNumber' || key !== 'pageSize') {
                    formParams.value[key] = undefined
                }
            }
            emit('refresh')
        }
        return () => (
            <ElForm v-show={ props.FormShow } model={formParams.value} {...props.FormAttrs}  >
                {formRules.value.map(item => {
                    return (
                        <ElFormItem {...item.props}>
                            {arrangeAssignment(item, formParams.value)}
                        </ElFormItem>
                    )
                })}
                <ElFormItem>
                    <ElButton type="primary" icon='Search' onClick={() => emit('submit')} >{'搜索'}</ElButton>
                    <ElButton icon='Refresh' onClick={handleRefresh} >{'重置'}</ElButton>
                </ElFormItem>
            </ElForm>
        )
    },
})

export default FormSearch
